package com.gin.kotlin.no_gay_alliance.activity.pm

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Message
import android.text.InputType
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.AbstractPagerListActivity
import com.gin.kotlin.no_gay_alliance.adapter.pm.PrivateMessageUserAdapter
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.PrivateMessageReplyArgument
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.InputMethodUtils
import com.gin.kotlin.no_gay_alliance.databinding.ActivityPrivateMessageReplyBinding
import com.gin.kotlin.no_gay_alliance.enums.HandlerMessageWhat
import com.gin.kotlin.no_gay_alliance.fragment.pm.AbstractPrivateMessageReplyPageFragment
import com.gin.kotlin.no_gay_alliance.fragment.pm.PrivateMessageReplyHtmlFragment
import com.gin.kotlin.no_gay_alliance.webview.BbsCodeWebViewPool
import com.gin.nga.callback.NgaCallback
import com.gin.nga.response.base.NgaResponse
import com.gin.nga.response.user.TinyUserInfo
import retrofit2.Call
import retrofit2.Response

/**
 * 私信回复活动
 * @property bbsCodeWebViewPool WebView池
 * @property users 参与的用户列表
 * @property argument PrivateMessageReplyArgument
 * @property currentFragment 当前页Fragment
 */
class PrivateMessageReplyActivity : AbstractPagerListActivity<ActivityPrivateMessageReplyBinding>() {
    private lateinit var argument: PrivateMessageReplyArgument
    lateinit var bbsCodeWebViewPool: BbsCodeWebViewPool
    private var users: List<TinyUserInfo>? = null
    var currentFragment: AbstractPrivateMessageReplyPageFragment? = null

    override fun refresh() {
        currentFragment?.refresh()
    }

    override fun onActivityResult(result: ActivityResult) {
        super.onActivityResult(result)
        if (result.resultCode == 200) {
            refresh()
        } else {
            Log.i(TAG, "onActivityResult: ${result.resultCode}")
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, menuInflater)
        if (!argument.fromSystem) menuInflater.inflate(R.menu.private_message_reply, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.mi_private_message_user_list) {
            // 弹窗管理当前用户
            Log.i(TAG, "当前私信参与用户: ${this.users?.mapNotNull { it.username }}")

            val recyclerView = RecyclerView(this)
            recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
            recyclerView.adapter = PrivateMessageUserAdapter(argument.messageId, this, handler!!, users?.toMutableList() ?: mutableListOf())
            AlertDialogUtils.builder(this,"会话中的用户", contentView = recyclerView).show()
        }

        if (item.itemId == R.id.mi_private_message_user_new) {
            // 邀请用户
            val editText = EditText(this)
            editText.maxLines = 5
            editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE
            editText.requestFocus()
            editText.selectAll()

            AlertDialogUtils.builder(
                this,
                getString(R.string.dialog_title_pm_invite_user),
                getString(R.string.dialog_message_invite_user),
                editText
            ) { _, which ->
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    val users = arrayListOf(* editText.text.toString().split(" ").map { it.trim() }.filter { it.isNotEmpty() }.toTypedArray())
                    if (users.isEmpty()) {
                        toast("用户不能为空")
                        return@builder
                    }
                    App.INSTANCE.ngaApi.messageApi.add(argument.messageId, users).enqueue(object : NgaCallback<List<String>> {
                        override fun onSuccess(
                            call: Call<NgaResponse<List<String>>>,
                            response: Response<NgaResponse<List<String>>>,
                            body: NgaResponse<List<String>>?,
                            data: List<String>?
                        ) {
                            // 邀请成功，翻到第一页刷新
                            data?.get(0)?.also { toast(it) }
                            b?.viewPager2?.currentItem = 0
                            uiDelayed(500) { refresh() }
                        }

                        override fun onError(
                            call: Call<NgaResponse<List<String>>>,
                            response: Response<NgaResponse<List<String>>>,
                            body: NgaResponse<List<String>>?,
                            errorMessage: String
                        ) {
                            toastLong(errorMessage)
                        }
                    })
                }
            }.show()

            uiDelayed(500) { InputMethodUtils.show(editText) }
        }


        return super.onOptionsItemSelected(item)
    }


    override fun handleMessage(msg: Message): Boolean {
        if (msg.what == HandlerMessageWhat.PRIVATE_MESSAGE_USER.ordinal) {
            @Suppress("UNCHECKED_CAST")
            this.users = msg.obj as List<TinyUserInfo>
            Log.i(TAG, "当前私信参与用户: ${this.users?.mapNotNull { it.username }}")
        }
        return super.handleMessage(msg)
    }

    override fun launchPostActivity(launcher: ActivityResultLauncher<Intent>) {
        //  点击发帖按钮，回复私信
        val intent = Intent(this, PrivateMessagePostActivity::class.java)
        intent.putExtra("id", argument.messageId)
        launcher.launch(intent)
    }

    override fun onCreate() {
        updatePage(1, argument.totalPage ?: 1)

        if (argument.fromSystem) b?.floatButtonPost?.visibility = View.GONE

        // 正文WebView池
        this.bbsCodeWebViewPool = BbsCodeWebViewPool(this)

        // 装载适配器
        this.b?.viewPager2?.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount() = totalPage
            override fun createFragment(position: Int) = PrivateMessageReplyHtmlFragment.newInstance(argument.copy(page = position + 1))
        }
    }

    override fun handleIntent(intent: Intent) {
        this.argument = parseArgument(intent, PrivateMessageReplyArgument::class.java.simpleName, PrivateMessageReplyArgument::class.java)
    }

    override fun onResume() {
        super.onResume()
        argument.title?.also { setToolbarTitle(it) }
    }

    companion object {
        @JvmStatic
        fun start(context: Context, argument: PrivateMessageReplyArgument) {
            val starter = Intent(context, PrivateMessageReplyActivity::class.java)
                .putExtra(PrivateMessageReplyArgument::class.java.simpleName, argument)
            context.startActivity(starter)
        }
    }

}